package com.eshipenet.shipnet.shiprpc.server;


import akka.actor.AbstractActor;
import akka.actor.ActorSystem;
import akka.actor.Props;
import com.eshipenet.shipnet.ship.ShipGovernor;
import com.eshipenet.shipnet.shiprpc.grpc.ShipGovernorLinkRepoGrpcImpl;
import com.eshipenet.shipnet.shiprpc.grpc.ShipGovernorRepoGrpcImpl;
import com.eshipenet.shipnet.shiprpc.grpc.ShipOwnerRepoGrpcImpl;
import com.eshipenet.shipnet.shiprpc.grpc.ShipRepoGrpcImpl;
import com.eshipenet.shipnet.shiprpc.ignite.ShipIgnite;
import com.eshipenet.shipnet.shiprpc.service.ShipGovernorLinkService;
import com.eshipenet.shipnet.shiprpc.service.ShipGovernorService;
import com.eshipenet.shipnet.shiprpc.service.ShipOwnerService;
import com.eshipenet.shipnet.shiprpc.service.ShipService;
import io.grpc.ServerBuilder;
import io.grpc.protobuf.services.ProtoReflectionService;
import org.apache.ignite.Ignite;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.Ignition;
import org.apache.ignite.configuration.CacheConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


class ShipActor extends AbstractActor {

    static Props props() {
        return Props.create(ShipActor.class, ShipActor::new);
    }

    @Override
    public void preStart() throws Exception {

        Ignite ignite = Ignition.ignite("Ship");

        ShipGovernorService shipGovernorService = ignite.services().service("ShipGovernorService");
        ShipOwnerService shipOwnerService = ignite.services().service("ShipOwnerService");
        ShipService shipService = ignite.services().service("ShipService");
        ShipGovernorLinkService shipGovernorLinkService = ignite.services().service("ShipGovernorLinkService");

        ServerBuilder.forPort(50051)
                .addService(new  ShipGovernorRepoGrpcImpl(shipGovernorService))
                .addService(new ShipOwnerRepoGrpcImpl(shipOwnerService))
                .addService(new ShipRepoGrpcImpl(shipService,shipOwnerService))
                .addService(new ShipGovernorLinkRepoGrpcImpl(shipGovernorLinkService,shipGovernorService,shipService))
                .addService(ProtoReflectionService.newInstance())
                .build()
                .start();

    }

    @Override
    public void postStop() {
        System.out.println("stopped...");
    }


    @Override
    public Receive createReceive() {
        return receiveBuilder().matchAny(t -> {
            getSender().tell(t, getSelf());
            //停止
            //getContext().stop(getSelf());
        }).build();

    }


    public static void main(String[] args) {
        Logger logger = LoggerFactory.getLogger("ShipActor");
        logger.debug("ignite start");
        ShipIgnite.ignite();
        ActorSystem system = ActorSystem.create("shiprpc");
        system.actorOf(ShipActor.props(), "RPCServer");
    }
}





